~今天要分享的是「隨機森林實作」~
在理解了隨機森林的基本原理後來看看python程式碼如何實作的吧~
隨機森林分析模型在sklearn的ensemble套件底下:from sklearn import ensemble
#使用在分類問題ensemble.RandomForestClassifier()
#使用在迴歸問題ensemble.RandomForestRegressor()
在實作前有兩個重點先告訴大家:
[程式碼實作]
迴歸問題:使用sklearn的資料集”boston”進行分析,n_estimators設定為15
import pandas as pd
from sklearn.datasets import load_boston
boston = load_boston()
boston_data=pd.DataFrame(boston['data'],columns=boston['feature_names'])
print("Data:",boston_data.head())
print("====================================")
boston_target=pd.DataFrame(boston['target'],columns=['target'])
print("Target:",boston_target.head())
print("====================================")
X=boston_data[["CRIM",'ZN',"INDUS","CHAS","NOX","RM","AGE","DIS","RAD","TAX","PTRATIO","B","LSTAT"]]
y=boston_target['target']
from sklearn.model_selection import train_test_split
X_train, X_test,y_train,y_test = train_test_split(X,y,test_size=0.3)
from sklearn import ensemble
RFR=ensemble.RandomForestRegressor(n_estimators=15,oob_score = True)
RFR.fit(X_train,y_train)
print('特徵重要程度:',RFR.feature_importances_)
print('oob score:',RFR.oob_score_)
print("解釋力:",RFR.score(X_test,y_test))
from sklearn.metrics import mean_squared_error
from math import sqrt
RFR_pred =RFR.predict(X_test)
rmse = sqrt(mean_squared_error(y_test, RFR_pred))
print("rmse: %.3f" % rmse)
print("依變數平均值:",boston_target['target'].mean())
由結果可以得知,自變數X對目標值依變數Y的特徵重要程度分別是:"CRIM"(約0.056), 'ZN'(約0.002), "INDUS"(約0.007), "CHAS"(約0.0005), "NOX"(約0.033), "RM"(約0.416), "AGE"(約0.013), "DIS"(約0.069), "RAD"(約0.006), "TAX"(約0.015), "PTRATIO"(約0.014), "B"(約0.013), "LSTAT"(約0.357),其中' RM '為分類能力最好的特徵。
另外分析結果也指出,此模型的泛化能力有約0.80,解釋力約有0.89,且目標變數裡的數據平均值約為22.53,模型誤差只有約3.704,所以算是蠻優良的模型。
分類問題:使用sklearn的資料集”iris”進行分析,n_estimators設定為5
import pandas as pd
from sklearn.datasets import load_iris
iris = load_iris()
iris_data = pd.DataFrame(iris['data'],columns=iris['feature_names'])
print("Data:",iris_data.head())
print("====================================")
iris_target=pd.DataFrame(iris['target'],columns=['target'])
print("Target:",iris_target.head())
print("====================================")
X=iris_data[['sepal length (cm)','sepal width (cm)','petal length (cm)','petal width (cm)']]
y=iris_target['target']
from sklearn.model_selection import train_test_split
X_train, X_test,y_train,y_test = train_test_split(X,y,test_size=0.3)
from sklearn import ensemble
RFC=ensemble.RandomForestClassifier(n_estimators=5,oob_score = True)
RFC.fit(X_train,y_train)
print('特徵重要程度:',RFC.feature_importances_)
print('oob score:',RFC.oob_score_)
from sklearn.metrics import classification_report,confusion_matrix
RFC_pred= RFC.predict(X_test)
print("混淆矩陣:",confusion_matrix(y_test,RFC_pred))
print("======================================================\n")
print("模型驗證指標:",classification_report(y_test,RFC_pred))
由結果可以得知,自變數X對目標值依變數Y的特徵重要程度分別是:'sepal length (cm)'(約0.022), 'sepal width (cm)'(約0.014), 'petal length (cm)'(約0.463), 'petal width (cm)'(約0.501),其中' petal width (cm)'為分類能力最好的特徵。
另外分析結果也指出,測試資料中有兩筆原本分類為第2類的樣本被模型預測成第1類,以及一筆原本分類為第1類的樣本被模型預測成第2類,因此出現了一點誤差,但整體正確率高達0.93,且此模型的泛化能力有約0.90,所以是一個蠻優秀的模型。